﻿using System;
using System.Collections.Generic;
using System.Text;
using reactiveBT.Utilities;

namespace reactiveBT.BT
{
    /// <summary>
    /// 选择分支节点
    /// 具有单Tick多节点特性
    /// 当子节点Success次数达到指定次数时返回Success。遍历子结点过程返回Continue
    /// 当遍历所有子结点仍然未达到指定Success次数时返回Failure
    /// 向上传递Abort
    /// </summary>
    public class Selector : Branch
    {
        int successCount = 1;
        int currentCount = 0;
        public Selector(int count = 1)
        {
            successCount = count;
        }
        public override BTState Tick(int BTid)
        {
            if(needToReset)
            {
                this.ResetSelf();
                base.ResetChildren();
                needToReset = false;
            }
            while (true)
            {
                var result = children[activeChild].Tick(BTid);
                switch (result)
                {
                    case BTState.Success:
                        currentCount++;
                        if (currentCount == successCount)
                        {
                            needToReset = true;
                            return BTState.Success;
                        }
                        return BTState.Continue;
                    case BTState.Failure:
                        activeChild++;
                        if (activeChild == children.Count)
                        {
                            needToReset = true;
                            return BTState.Failure;
                        }
                        else
                            continue;
                    case BTState.Continue:
                        return BTState.Continue;
                    case BTState.Abort:
                        needToReset = true;
                        return BTState.Abort;
                }
            }
            //impossible
            throw new System.Exception("never happen");
        }
        protected override void ResetSelf()
        {
            base.ResetSelf();
            currentCount = 0;
        }
    }
}
